In [1]:
import tensorflow as tf
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:529: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:530: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\dtypes.py:535: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
In [3]:
print(tf._version_)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-3-9ede5474d7f7> in <module>
----> 1 print(tf._version_)

AttributeError: module 'tensorflow' has no attribute '_version_'
In [4]:
hello=tf.constant("hello")
In [6]:
type(hello)
Out[6]:
tensorflow.python.framework.ops.Tensor
In [23]:
world = tf.constant("World")
type(world)
with tf.Session() as sess:
        result= sess.run(hello+world)
In [25]:
print(result)
b'helloWorld'
In [27]:
a=tf.constant(10)
b=tf.constant(20)
In [29]:
a
Out[29]:
<tf.Tensor 'Const_11:0' shape=() dtype=int32>
In [31]:
with tf.Session() as sess:
    result = sess.run(a+b)
    
In [33]:
print(result)
30
In [37]:
const=tf.constant(10)
fill_mat=tf.fill((4,4),10)
myzeros = tf.zeros((4,4))
myones = tf.ones((4,4))
myrandn=tf.random_normal((4,4),mean=0,stddev=1.0)
myrandu= tf.random_uniform((4,4),minval=0,maxval=1)
my_ops = [const,fill_mat,myzeros,myones,myrandn,myrandu]
sess= tf.InteractiveSession()
for op in my_ops:
    print(sess.run(op))
    print("\n")
10


[[10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]
 [10 10 10 10]]


[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]


[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]


[[ 0.26085314 -1.0023993  -0.23326488  0.5901882 ]
 [ 0.05536489 -2.0925837   1.3016802  -0.9761187 ]
 [-1.4803563  -0.57226956 -0.38804996  0.07187255]
 [ 2.2740564  -0.736991   -1.0595205   1.4164616 ]]


[[0.19111168 0.6370064  0.00978029 0.58018184]
 [0.5877969  0.68713117 0.8140515  0.09573078]
 [0.7898443  0.26656651 0.73091996 0.1618905 ]
 [0.18500054 0.40711963 0.94082654 0.24062777]]


C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py:1702: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).
  warnings.warn('An interactive session is already active. This can '
In [40]:
a= tf.constant([[1,2],[3,4]])
a.get_shape()
b=tf.constant([[10],[20]])
b.get_shape()
result=tf.matmul(a,b)
sess.run(result)
Out[40]:
array([[ 50],
       [110]])
In [42]:
import tensorflow as tf
n1 = tf.constant(1)
n2=tf.constant(2)
n3 = n1+n2
with tf. Session() as sess:
    result =sess.run(n3)
    print(result)
3
In [47]:
sess=tf.InteractiveSession()
my_tensor = tf.random_uniform((4,4),0,1)
my_tensor
my_var = tf.Variable(initial_value=my_tensor)
print(my_var)
init =tf.global_variables_initializer()
sess.run(init)
sess.run(my_var)
<tf.Variable 'Variable_3:0' shape=(4, 4) dtype=float32_ref>
Out[47]:
array([[0.86593664, 0.24557471, 0.95057046, 0.35477948],
       [0.3593508 , 0.16969252, 0.0840714 , 0.06581891],
       [0.14786196, 0.96240187, 0.42087793, 0.0690707 ],
       [0.67133355, 0.22046542, 0.57506347, 0.09641814]], dtype=float32)
In [50]:
ph = tf.placeholder(tf.float32,shape=(None,4))
In [75]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf
x_data = np.linspace(0.0,10.0,1000000)
noise =np.random.randn(len(x_data))
noise
Out[75]:
array([-1.45594924, -0.20849513, -0.37708331, ...,  2.43971267,
        0.70331977,  1.05530788])
In [76]:
noise
Out[76]:
array([-1.45594924, -0.20849513, -0.37708331, ...,  2.43971267,
        0.70331977,  1.05530788])
In [70]:
 
Out[70]:
X-Data Y
0 0.00000 5.410899
1 0.00001 5.522333
2 0.00002 5.561065
3 0.00003 6.598669
4 0.00004 2.737949
In [66]:
x_data
Out[66]:
array([0.000000e+00, 1.000001e-05, 2.000002e-05, ..., 9.999980e+00,
       9.999990e+00, 1.000000e+01])
In [132]:
my_data.sample(n=300).plot(kind='scatter',x='X_Data',y='Y')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3077             try:
-> 3078                 return self._engine.get_loc(key)
   3079             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'X_Data'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-132-14e1978eaf25> in <module>
----> 1 my_data.sample(n=300).plot(kind='scatter',x='X_Data',y='Y')

C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   2939                           fontsize=fontsize, colormap=colormap, table=table,
   2940                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2941                           sort_columns=sort_columns, **kwds)
   2942     __call__.__doc__ = plot_frame.__doc__
   2943 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   1975                  yerr=yerr, xerr=xerr,
   1976                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1977                  **kwds)
   1978 
   1979 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
   1741         if isinstance(data, ABCDataFrame):
   1742             plot_obj = klass(data, x=x, y=y, subplots=subplots, ax=ax,
-> 1743                              kind=kind, **kwds)
   1744         else:
   1745             raise ValueError("plot kind %r can only be used for data frames"

C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __init__(self, data, x, y, s, c, **kwargs)
    843             # the handling of this argument later
    844             s = 20
--> 845         super(ScatterPlot, self).__init__(data, x, y, s=s, **kwargs)
    846         if is_integer(c) and not self.data.columns.holds_integer():
    847             c = self.data.columns[c]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __init__(self, data, x, y, **kwargs)
    817         if is_integer(y) and not self.data.columns.holds_integer():
    818             y = self.data.columns[y]
--> 819         if len(self.data[x]._get_numeric_data()) == 0:
    820             raise ValueError(self._kind + ' requires x column to be numeric')
    821         if len(self.data[y]._get_numeric_data()) == 0:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2686             return self._getitem_multilevel(key)
   2687         else:
-> 2688             return self._getitem_column(key)
   2689 
   2690     def _getitem_column(self, key):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
   2693         # get column
   2694         if self.columns.is_unique:
-> 2695             return self._get_item_cache(key)
   2696 
   2697         # duplicate columns & possible reduce dimensionality

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
   2487         res = cache.get(item)
   2488         if res is None:
-> 2489             values = self._data.get(item)
   2490             res = self._box_item_values(item, values)
   2491             cache[item] = res

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
   4113 
   4114             if not isna(item):
-> 4115                 loc = self.items.get_loc(item)
   4116             else:
   4117                 indexer = np.arange(len(self.items))[isna(self.items)]

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3078                 return self._engine.get_loc(key)
   3079             except KeyError:
-> 3080                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   3081 
   3082         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'X_Data'
In [ ]:
y_true = (0.5*x_data)+5+noise
x_df= pd.DataFrame(data=x_data,columns = ['X Data'])
y_df = pd.DataFrame(data=y_true,columns=['Y'])
my_data=pd.concat([x_df,y_df],axis=1)
my_data.head()
my_data.sample(n=300).plot(kind='scatter',x='X Data',y='Y')
In [142]:
batch_size =10
m=tf.Variable(2.5)
b=tf.Variable(2.0)
xph = tf.placeholder(tf.float32,[batch_size])
yph= tf.placeholder(tf.float32,[batch_size])
y_model= m*xph+b
error= tf.reduce_sum(tf.square(yph-y_model))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train =optimizer.minimize(error)
init =tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    batches =1000
    
    for i in range(batches):
        rand_ind =np.random.randint(len(x_data), size=batch_size)
        feed = {xph: x_data[rand_ind],yph:y_true[rand_ind]}
        sess.run(train, feed_dict = feed)
        model_m, model_b = sess.run([m,b])
        y_hat = x_data*model_m + model_b
        my_data.sample(300).plot(kind = 'scatter',x='X Data', y='Y')
    
In [146]:
Feat_cols =[tf.feature_column.numeric_column('x',shape=[1])]
estimator =tf.estimator.LinearRegressor(feature_columns=Feat_cols)

from sklearn.model_selection import train_test_split
X_train,X_test, y_train, y_test = train_test_split(x_data,y_true, test_size=0.3,random_state=42)
print(X_train.shape)
INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: C:\Users\ADMINI~1\AppData\Local\Temp\tmpoktr4aws
INFO:tensorflow:Using config: {'_model_dir': 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmpoktr4aws', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_service': None, '_cluster_spec': <tensorflow.python.training.server_lib.ClusterSpec object at 0x0000024240E432E8>, '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}
(700000,)
In [189]:
X_test.shape
input_func= tf.estimator.inputs.numpy_input_fn({'x': X_train}, y_train, batch_size =10, num_epochs =None,shuffle=True)
train_input_func= tf.estimator.inputs.numpy_input_fn({'x': X_train}, y_train, batch_size =10, num_epochs =1000,shuffle= False)
test_input_func= tf.estimator.inputs.numpy_input_fn({'x': X_test}, y_test, batch_size =10, num_epochs = 1000,shuffle= False)
estimator.train(input_fn = input_func, steps=1000)
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from C:\Users\ADMINI~1\AppData\Local\Temp\tmpoktr4aws\model.ckpt-2000
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Saving checkpoints for 2000 into C:\Users\ADMINI~1\AppData\Local\Temp\tmpoktr4aws\model.ckpt.
INFO:tensorflow:loss = 10.352438, step = 2001
INFO:tensorflow:global_step/sec: 330.037
INFO:tensorflow:loss = 24.117647, step = 2101 (0.303 sec)
INFO:tensorflow:global_step/sec: 909.08
INFO:tensorflow:loss = 6.2175217, step = 2201 (0.110 sec)
INFO:tensorflow:global_step/sec: 925.936
INFO:tensorflow:loss = 13.625464, step = 2301 (0.108 sec)
INFO:tensorflow:global_step/sec: 1010.1
INFO:tensorflow:loss = 4.950808, step = 2401 (0.099 sec)
INFO:tensorflow:global_step/sec: 934.564
INFO:tensorflow:loss = 7.865534, step = 2501 (0.107 sec)
INFO:tensorflow:global_step/sec: 925.934
INFO:tensorflow:loss = 18.47582, step = 2601 (0.108 sec)
INFO:tensorflow:global_step/sec: 900.906
INFO:tensorflow:loss = 3.2278016, step = 2701 (0.112 sec)
INFO:tensorflow:global_step/sec: 934.576
INFO:tensorflow:loss = 12.316221, step = 2801 (0.106 sec)
INFO:tensorflow:global_step/sec: 943.39
INFO:tensorflow:loss = 5.350358, step = 2901 (0.106 sec)
INFO:tensorflow:Saving checkpoints for 3000 into C:\Users\ADMINI~1\AppData\Local\Temp\tmpoktr4aws\model.ckpt.
INFO:tensorflow:Loss for final step: 8.2927265.
Out[189]:
<tensorflow_estimator.python.estimator.canned.linear.LinearRegressor at 0x2427c987048>
train_metrics =estimator.evaluate(input_fn = train_input_func, steps=1000)